package com.springboot.demo.io.netty;

import java.net.InetSocketAddress;

import com.springboot.demo.constant.CommonConstant;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * netty 服务端
 *
 * @author supu
 * @since 2020-11-17 11:27
 **/
public class NettyServer {
    public static void main(String[] args) {
        NettyServer nettyServer = new NettyServer();
//        nettyServer.generalServer();
        nettyServer.nettySever();
    }

    public void generalServer() {

        System.out.println("server start。。。。。。");

        NioEventLoopGroup selector = new NioEventLoopGroup(1);

        NioServerSocketChannel server = new NioServerSocketChannel();

        selector.register(server);

        // accept 接受客户端，并且注册到 selector
        ChannelPipeline pipeline = server.pipeline();
        pipeline.addLast(new MyAcceptHandler(selector, new ChannelInit()));

        ChannelFuture bind = server.bind(new InetSocketAddress(CommonConstant.LOCALHOST, CommonConstant.LOCAL_PORT));

        try {
            bind.sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void nettySever() {
        System.out.println("server start。。。。。。");

        NioEventLoopGroup selector = new NioEventLoopGroup(1);
        ServerBootstrap bootstrap = new ServerBootstrap();
        // ChannelInitializer 等价于 ChannelInit
        ChannelFuture bind = bootstrap.group(selector).channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline.addLast(new MyInHandler());
                            }
                        }).bind(new InetSocketAddress(CommonConstant.LOCALHOST, CommonConstant.LOCAL_PORT));

        try {
            bind.sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
